package dominion.model.actions.base;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

import dominion.model.Card;
import dominion.model.GameBoard;
import dominion.model.Player;
import dominion.model.actions.Action;
import dominion.model.points.Points;
import dominion.utils.Constants;

public class Bureaucrat extends Action {

	public Bureaucrat() {
		cost = 4;
	}

	@Override
	public Card clone() {
		return new Bureaucrat();
	}

	@Override
	public String toString() {
		return "Bureaucrat";
	}

	@Override
	public String getDescription() {
		StringBuffer sb = new StringBuffer();
		sb.append(super.getDescription());
		sb.append("Gain a silver card and put it on top of your deck.\n");
		sb.append("Each other player reveals a victory card from his hand and puts it on his deck\n");
		sb.append("(or reveals a hand with no victory cards)\n");
		return sb.toString();
	}

	@Override
	public void doAction(Player player, GameBoard board, List<Player> players) throws IOException {
		player.changeAction(-1);
		playedCard(player);

		Constants.printer.print("Gained a silver.");
		player.addToDeck(board.drawFromSilver(), Constants.LIBRARY_DECK);

		for (Player current : players)
		{
			if (current.equals(player))
			{
				continue;
			}
			if (current.hasCounter())
			{
				Constants.printer.print(current.getName() + " has Moat and is unaffected.");
			}
			else if (!playerHasVictory(current))
			{
				Constants.printer.print(current.getName() + " has no victory cards. Here is the hand: ");
				Constants.printer.print(current.printHand());
			}
			else
			{
				Constants.printer.print(current.getName() + ": Please choose a victory card to move to deck:");
				Constants.printer.print(current.printHand());
				boolean done = false;
				BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
				String choice = null;
				while (!done && !current.getHand().isEmpty())
				{
					choice = in.readLine().trim().toLowerCase();
					Card card = Constants.cardMap.get(choice);
					if (card == null)
					{
						Constants.printer.print("Invalid card.");
					}
					else if (!current.getHand().contains(card))
					{
						Constants.printer.print("Card is not in hand.");
					}
					else if (!(card instanceof Points))
					{
						Constants.printer.print("Must choose a victory card.");
					}
					else
					{
						Card choosen = current.drawFromDeck(choice, Constants.HAND);
						current.addToDeck(choosen, Constants.LIBRARY_DECK);
						done = true;
					}
				}
			}
		}
	}

	private boolean playerHasVictory(Player player) {
		boolean result = false;
		for (Card card : player.getHand().getList())
		{
			if (card instanceof Points)
			{
				result = true;
			}
		}
		return result;
	}
}
